﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class NewBehaviourScript : MonoBehaviour
{
    private Dictionary<string, string> file = new Dictionary<string, string>();
    string filePath = Directory.GetCurrentDirectory() + "/binaryFile.txt";
   
    // Use this for initialization
    void Start()
    {
        string path = Application.dataPath + "/binaryFile.txt";
        file.Add("1", "wuzhang");
        file.Add("2", "zhangsan");
        file.Add("3", "李四");

        //Serialize(file, path);
        //反序列化
        file = DeSerialize<Dictionary<string, string>>(path);
        foreach (var item in file)
        {
            Debug.Log(item.Key + " " + item.Value);
        }

        CreateObject createObject = new CreateObject();
    }

    public void Serialize<T>(T t,string path)
    {
        Debug.Log(path);
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(path, FileMode.OpenOrCreate,FileAccess.Write,FileShare.None);
            formatter.Serialize(stream, t);
            stream.Flush();
            stream.Close();
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
        }
    }


    public T DeSerialize<T>(string path)
    {
        if (!File.Exists(path))
            return default(T);
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            T t =(T)formatter.Deserialize(stream);
            stream.Flush();
            stream.Close();
            return t;
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
        }
        return default(T);

    }
}
